﻿using Newtonsoft.Json.Linq;
using PlaneClean.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace PlaneClean.Filter
{
    /// <summary>
    /// 验证登录过滤器
    /// </summary>
    public class LoginFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            //base.OnActionExecuting(actionContext);
            bool requireLogin = actionContext.ActionDescriptor.GetCustomAttributes<NotLoginFilter>().Count == 0;//查询是否有不需要登录过滤器
            if (!requireLogin) return; //如果有不需要登录过滤器直接返回
            var requestContent = actionContext.Request.Content.ReadAsStringAsync();//读取post提交的json数据
            requestContent.Wait();//等待异步读取结束
            var inputJson = requestContent.Result;//请求json的数据
            JObject json = JObject.Parse(inputJson);//json数据转换成json对象 json["token"]方式获取具体数据

            if (json["token"] == null || json["token"].ToString() == "")
            {
                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ObjectContent<BaseResponse>(
                          new BaseResponse() { result = "NG", reason = "请求token不能为空" },
                          new JsonMediaTypeFormatter(),
                          "text/json"
                          )
                };
                return;
            }
            string token = json["token"].ToString();
            LoginInfo loginInfo = HttpContext.Current.Session[token] as LoginInfo;
            if (loginInfo == null)
            {
                actionContext.Response = new HttpResponseMessage()
                {
                    StatusCode = HttpStatusCode.OK,
                    Content = new ObjectContent<BaseResponse>(
                       new BaseResponse() { result = "NG", reason = "未登录或登录已超时,请重新登录"},
                       new JsonMediaTypeFormatter(),
                       "text/json"
                       )
                };
                return;
            }
            base.OnActionExecuting(actionContext);
        }
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }
}